package com.ruoyi.system.service.impl;

import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

import cn.wildfirechat.pojos.InputOutputUserInfo;
import cn.wildfirechat.pojos.OutputGroupMemberList;
import cn.wildfirechat.pojos.PojoGroupInfo;
import cn.wildfirechat.pojos.PojoGroupMember;
import cn.wildfirechat.proto.ProtoConstants;
import cn.wildfirechat.sdk.GroupAdmin;
import cn.wildfirechat.sdk.UserAdmin;
import cn.wildfirechat.sdk.model.IMResult;
import com.ruoyi.system.domain.GroupMember;
import com.ruoyi.system.dto.GroupMemberDTO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import com.ruoyi.system.mapper.TGroupMapper;
import com.ruoyi.system.domain.TGroup;
import com.ruoyi.system.service.ITGroupService;

/**
 * max group member countService业务层处理
 * 
 * @author ruoyi
 * @date 2025-08-18
 */
@Service
public class TGroupServiceImpl implements ITGroupService 
{
    @Autowired
    private TGroupMapper tGroupMapper;

    @Value("${admin:admin}")
    private String admin;

    /**
     * 查询max group member count
     * 
     * @param id max group member count主键
     * @return max group member count
     */
    @Override
    public TGroup selectTGroupById(Long id)
    {
        return tGroupMapper.selectTGroupById(id);
    }

    /**
     * 查询max group member count列表
     * 
     * @param tGroup max group member count
     * @return max group member count
     */
    @Override
    public List<TGroup> selectTGroupList(TGroup tGroup)
    {
        return tGroupMapper.selectTGroupList(tGroup);
    }

    /**
     * 新增max group member count
     * 
     * @param tGroup max group member count
     * @return 结果
     */
    @Override
    public Boolean insertTGroup(TGroup tGroup)
    {
        PojoGroupInfo groupInfo = new PojoGroupInfo();
        groupInfo.setOwner(tGroup.getOwner());
        groupInfo.setName(tGroup.getName());
        groupInfo.setExtra(tGroup.getExtra());
        groupInfo.setType(2);
        groupInfo.setPortrait(tGroup.getPortrait());
        try {
            GroupAdmin.createGroup(tGroup.getOwner(),groupInfo,tGroup.getMemberList(),null,null,null);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return true;
    }

    /**
     * 修改max group member count
     * 
     * @param tGroup max group member count
     * @return 结果
     */
    @Override
    public int updateTGroup(TGroup tGroup)
    {
        try {
            IMResult<PojoGroupInfo> groupInfo = GroupAdmin.getGroupInfo(tGroup.getGid());
            PojoGroupInfo result = groupInfo.getResult();
            // 0 群名
            if (!result.getName().equals(tGroup.getName())){
                GroupAdmin.modifyGroupInfo(tGroup.getOwner(), tGroup.getGid(), ProtoConstants.ModifyGroupInfoType.Modify_Group_Name,tGroup.getName(), null, null);

            }
            // 1 群头像
            if (!result.getPortrait().equals(tGroup.getPortrait())){
                GroupAdmin.modifyGroupInfo(tGroup.getOwner(), tGroup.getGid(), ProtoConstants.ModifyGroupInfoType.Modify_Group_Portrait,tGroup.getPortrait(), null, null);

            }
            //2 群extra
            if (!result.getExtra().equals(tGroup.getExtra())){
                GroupAdmin.modifyGroupInfo(tGroup.getOwner(), tGroup.getGid(), ProtoConstants.ModifyGroupInfoType.Modify_Group_Extra,tGroup.getExtra(), null, null);

            }
            // 3 群全局禁言
            if (result.getMute() != tGroup.getMute()){
                GroupAdmin.modifyGroupInfo(tGroup.getOwner(), tGroup.getGid(), ProtoConstants.ModifyGroupInfoType.Modify_Group_Mute,tGroup.getMute().toString(), null, null);

            }
            // 5 禁止私聊
            if (result.getPrivate_chat() != tGroup.getPrivateChat()){
                GroupAdmin.modifyGroupInfo(tGroup.getOwner(), tGroup.getGid(), ProtoConstants.ModifyGroupInfoType.Modify_Group_PrivateChat,tGroup.getPrivateChat().toString(), null, null);

            }
            // 8 群组最大成员数
            if (result.getMax_member_count() != tGroup.getMaxMemberCount()){
                GroupAdmin.modifyGroupInfo(tGroup.getOwner(), tGroup.getGid(), ProtoConstants.ModifyGroupInfoType.Modify_Group_Max_Member_Count,tGroup.getMaxMemberCount().toString(), null, null);
            }
           if (tGroup.getOwner() != result.getOwner()) {
                // 更新群主
                GroupAdmin.transferGroup(result.getOwner(), tGroup.getGid(), tGroup.getOwner(), null, null);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        // 0 群名, 1 群头像, 2 群extra, 3 群全局禁言, 4 群加入方式, 5 禁止私聊, 6 是否允许搜索群组, 7 是否允许新成员查看历史消息, 8 群组最大成员数
        return 1;
    }

    /**
     * 批量删除max group member count
     * 
     * @param ids 需要删除的max group member count主键
     * @return 结果
     */
    @Override
    public int deleteTGroupByIds(Long[] ids)
    {
        return tGroupMapper.deleteTGroupByIds(ids);
    }

    /**
     * 删除max group member count信息
     * 
     * @param id max group member count主键
     * @return 结果
     */
    @Override
    public int deleteTGroupById(Long id)
    {
        try {
            GroupAdmin.dismissGroup(admin,id.toString(),null,null);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return 1;
    }

    @Override
    public List<GroupMemberDTO> listByGroupMember(String groupId) {
        try {
            IMResult<OutputGroupMemberList> groupMembers = GroupAdmin.getGroupMembers(groupId);
            OutputGroupMemberList result = groupMembers.getResult();
            List<GroupMemberDTO> dtos = new ArrayList<>();
            for (PojoGroupMember member : result.getMembers()) {
                GroupMemberDTO groupMemberDTO = new GroupMemberDTO();
                // 查询用户信息
                IMResult<InputOutputUserInfo> user = UserAdmin.getUserByUserId(member.getMember_id());
                if (user.getResult() != null){
                    groupMemberDTO.setMemberName(user.getResult().getDisplayName());
                    groupMemberDTO.setMember(user.getResult().getName());
                }
                BeanUtils.copyProperties(member,groupMemberDTO);
                if (member.getCreateDt() != 0){
                    LocalDateTime ldt =
                        LocalDateTime.ofInstant(Instant.ofEpochMilli(member.getCreateDt()), ZoneId.systemDefault());
                    DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
                    groupMemberDTO.setTime(ldt.format(fmt));
                }
                dtos.add(groupMemberDTO);
            }
            return dtos;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public int groupMemberAddOrDel(TGroup tGroup) {
        if (tGroup.getAddOrDel() == 0){
            try {
                GroupAdmin.addGroupMembers(admin, tGroup.getGid(), tGroup.getMemberList(), null, null, null);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }else {
            try {
                List<String> collect = tGroup.getMemberList().stream().map(PojoGroupMember::getMember_id).collect(Collectors.toList());
                GroupAdmin.kickoffGroupMembers(admin, tGroup.getGid(), collect, null, null);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
        return 1;
    }
}
